#include "P0Wrap.h"
#include <QHash>
#include "p0parameter.h"

#pragma comment(lib,"P0Wrap\\P2PprotocolCPP.lib")

QHash<qint16,P0Paramer> P0Wrap::hashP0Parameter = QHash<qint16,P0Paramer>();
QHash<qint16,P2PprotocolCPP::P2PChannel*> P0Wrap::hashP0Channel = QHash<qint16,P2PprotocolCPP::P2PChannel*>();
QHash<int, QByteArray> P0Wrap::hashP0Data = QHash<int, QByteArray>();


void P0Wrap::start()
{
    P2PManager::start();
    P2PManager::setLogLevel("Error");
    P2PManager::setLogFile("p2pmgr.txt");
}

void P0Wrap::stop()
{
    P2PManager::stop();
}

void P0Wrap::p0Delete()
{
    //UdpPort ChannelOptions should delete?
}

 bool  P0Wrap::contain(int id)
 {
     return hashP0Channel.contains(id);
 }

void P0Wrap::onP0ReceiveData(P2PprotocolCPP::P2PChannel& channel,
                          unsigned char* data,
                          int length)
{
    quint32 did = channel.getDstId();

    QByteArray byte;
    byte.setRawData((const char*)data,length);
    hashP0Data.insert(did,byte);
}

void P0Wrap::Send(int id, QByteArray byte)
{
    P2PprotocolCPP::P2PChannel* p = hashP0Channel.value(id);
    Q_ASSERT( p != NULL);
    p->TryToSend((const unsigned char*)byte.data(),byte.size());

    //UInt32 iSendLen = 0;
    //        if ((tblP0Manager[Did]).bSendByBytes)
    //        {
    //            iSendLen = (tblP0Manager[Did]).sizeSend;
    //            logger.Debug("ZC to ATS MSG_TYPE = " + string.Format("{0:X4}", protocol.header[i].msgType));//should cbi
    //        }
    //        else
    //            iSendLen = (tblP0Manager[Did]).sizeSend / 8;
    //        byte[] bytes = new byte[iSendLen];
    //        System.Array.Copy(protocol.byteList[i], bytes, protocol.byteList[i].Length);
    //        (tblP0Manager[Did]).Send(bytes);

}

void P0Wrap::p0Create()
{
    XmlParser p;
    p.getP0Parameter(hashP0Parameter);
    qDebug() << "P0 parameters init finished!";

    QHash<qint16,P0Paramer>::const_iterator it = P0Wrap::hashP0Parameter.constBegin();
    while (it != hashP0Parameter.constEnd())
    {
         P0Paramer par = it.value();

         UdpPort* udpport = new UdpPort(qPrintable(par.localPeer),
                                     par.localPort,
                                     qPrintable(par.peer),
                                     par.remotePort);
         ChannelOptions *copt = new ChannelOptions(par.localPort,
                                                 par.remotePort,
                                                 par.sizeSend,
                                                 par.sizeRecv);
         copt->data_recv_callback = onP0ReceiveData;
         copt->data_send_callback = NULL;
         P2PprotocolCPP::P2PChannel* vch = new  P2PprotocolCPP::P2PChannel(*copt,*udpport);

         hashP0Channel.insert(it.key(), vch);
         ++it;
    }
}

void P0Wrap::cleanP0Data()
{
    hashP0Data.clear();
}